package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.exception.NoStockWareException;
import com.atguigu.common.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.excption.NostockException;
import com.atguigu.gulimall.ware.feign.CartFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.*;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }


            wareSkuDao.insert(skuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map((skuId) -> {
            SkuHasStockVo vos = new SkuHasStockVo();
            Long count = wareSkuDao.getSkuStock(skuId);
            vos.setSkuId(skuId);
            vos.setHasStock(count == null ? false : count > 0);
            return vos;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<OrderWareVo> selectByIds() {
        //拿到当前商品的skuid , 以及购买的数量
        //   查询改商品 再不同的仓库是否还有库存
        //   返回仓库的信息, 和 商品的 id 以及 数量 , 暂时不考虑 多仓库合并设计
        List<CartItemVo> cartItemVos = cartFeignService.getCartItemByMemberId();
        List<OrderWareVo> orderWareVos = cartItemVos.stream().map(item -> {
            Long skuid = item.getSkuid();
            Integer count = item.getCount();
            //进行 查库存, 和锁定库存的操作
            List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectWareBySkuIds(skuid, count);
            if (wareSkuEntities != null && wareSkuEntities.size() > 0) {
                //暂时不考虑仓库的就近原则
                WareSkuEntity wareSkuEntity = wareSkuEntities.get(0);
                OrderWareVo orderWareVo = new OrderWareVo();
                orderWareVo.setWareId(wareSkuEntity.getWareId());
                orderWareVo.setSkuName(wareSkuEntity.getSkuName());
                orderWareVo.setSkuId(skuid);
                //锁定库存
                wareSkuEntity.setStockLocked(wareSkuEntity.getStockLocked() + count);
                wareSkuDao.updateById(wareSkuEntity);
                return orderWareVo;
            } else {
                //存在商品没有库存的情况
                throw new NoStockWareException("商品库存不足", 18001);
            }
        }).collect(Collectors.toList());
        return orderWareVos;
    }

    @Transactional(rollbackFor = {NostockException.class})
    @Override
    public boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        // 保存库存工作单的详情
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //锁定库存
        String orderSn = wareSkuLockVo.getOrderSn();
        List<OrderItemVo> orderItemVos = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> skuWareHasStocks = orderItemVos.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuid = item.getSkuid();
            Integer count = item.getCount();
            //查询有库存
            List<Long> wareIds = wareSkuDao.hasStock(skuid, count);
            skuWareHasStock.setWareId(wareIds);
            skuWareHasStock.setSkuId(skuid);
            skuWareHasStock.setCount(count);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        //
        for (SkuWareHasStock skuWareHasStock : skuWareHasStocks) {
            boolean skuStock= false ;
            if (skuWareHasStock.getWareId() == null && skuWareHasStock.getWareId().size() == 0) {
                throw new NostockException(skuWareHasStock.getSkuId());
            } else {
                for (Long aLong : skuWareHasStock.getWareId()) {
                    Long  skuId = skuWareHasStock.getSkuId();
                    int count = skuWareHasStock.getCount();
                    Long result = wareSkuDao.updateStock(aLong,skuId,count);
                    if(result==1){
                        skuStock=true;
                       //库存锁定成功 , 更新库存工作单 , 和库存工作单详情
                        // 锁定成功 ,给Mw发送消息, 发送失败,事务全局回滚
                        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, null, count, wareOrderTaskEntity.getId(), aLong, 1);
                        wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                        StockLockedTo stockLockedTo = new StockLockedTo();
                        stockLockedTo.setDetailId(wareOrderTaskDetailEntity.getId());
                        stockLockedTo.setId(wareOrderTaskEntity.getId());
                        //锁定成功,使用mq发送消息
                        rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                        break;
                    }else {
                        //库存锁定失败
                    }
                }
                if(skuStock==false){
                    // 所有仓库均锁定失败
                    throw new NostockException(skuWareHasStock.getSkuId());
                }
            }
        }
        //成功
        return true;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private List<Long> WareId;
        private int count;

    }
}